package com.saturn.app

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.widget.TextView
import com.saturn.bean.User
import com.saturn.callback.IClientCallBack
import com.saturn.callback.IServerBusiness
import com.saturn.service.UploadService
import java.lang.ref.WeakReference

class MainActivity : AppCompatActivity() {

    private var mBusinessServer: IServerBusiness? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<TextView>(R.id.tv_start).setOnClickListener {
            toBindService()
        }



        findViewById<TextView>(R.id.tv_messenger_send).setOnClickListener {
            mBusinessServer?.login(123,"saturn")

        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unbindService(c)
    }


    val c : Connection by lazy {
        Connection(WeakReference(this))
    }

    private fun toBindService() {
        val intent = Intent(this, UploadService::class.java)
        bindService(intent,c,BIND_AUTO_CREATE)
    }

    private fun syncBinder(binder: IBinder?) {
        mBusinessServer = binder?.let {
            IServerBusiness.Stub.asInterface(it)
        }?.apply {
            register(ClientCallBackImpl())
        }
    }


    class Connection(val weak: WeakReference<MainActivity>) : ServiceConnection {

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            weak.get()?.syncBinder(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            weak.get()?.toBindService()
        }

    }


    class ClientCallBackImpl() : IClientCallBack.Stub(){

        override fun onCall(user: User?) {
            Log.e(TAG, "onCall $user")
        }
    }


    companion object {
       const val TAG = "ClientProcess"
    }

}